#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
从 dictionary.ts 同步词典的 tags 信息到数据库
"""

import json
import re
import pymysql
from datetime import datetime

DB_CONFIG = {
    'host': '127.0.0.1',
    'port': 3306,
    'user': 'root',
    'password': '123',
    'database': 'ry-vue',
    'charset': 'utf8mb4'
}

def parse_dictionary_ts(file_path):
    """解析 dictionary.ts 文件提取词典信息"""
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 存储词典信息
    dictionaries = []
    
    # 使用更精确的正则表达式匹配词典对象
    # 匹配整个词典对象块：从 { 开始到对应的 } 结束
    dict_pattern = r'\{[^}]*?id:\s*[\'"]([^\'"]+)[\'"][^}]*?tags:\s*\[([^\]]*)\][^}]*?\}'
    
    matches = re.finditer(dict_pattern, content, re.DOTALL)
    
    for match in matches:
        dict_id = match.group(1)
        tags_str = match.group(2)
        
        # 解析tags数组
        tags = []
        if tags_str.strip():
            # 提取所有引号中的内容
            tag_matches = re.findall(r'[\'"]([^\'"]+)[\'"]', tags_str)
            tags = [tag.strip() for tag in tag_matches if tag.strip()]
        
        if tags:  # 只添加有标签的词典
            dictionaries.append({
                'id': dict_id,
                'tags': tags
            })
    
    return dictionaries

def sync_dict_tags():
    """同步词典标签到数据库"""
    # 解析 dictionary.ts
    ts_file = '/root/workspace/3.1.0-dev/work/aiword/src/resources/dictionary.ts'
    print(f"正在解析文件: {ts_file}")
    
    dictionaries = parse_dictionary_ts(ts_file)
    print(f"找到 {len(dictionaries)} 个有标签的词典定义\n")
    
    # 连接数据库
    conn = pymysql.connect(**DB_CONFIG)
    try:
        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
            # 获取数据库中的所有词典
            cursor.execute("SELECT id, name FROM dict_book")
            db_books = {row['id']: row['name'] for row in cursor.fetchall()}
            print(f"数据库中有 {len(db_books)} 个词典\n")
            
            # 统计所有唯一的标签
            all_tags = set()
            for dict_info in dictionaries:
                all_tags.update(dict_info['tags'])
            print(f"总共发现 {len(all_tags)} 个不同的标签:")
            for tag in sorted(all_tags):
                print(f"  - {tag}")
            print()
            
            # 获取已存在的标签
            cursor.execute("SELECT id, name FROM dict_tag")
            existing_tags = {row['name']: row['id'] for row in cursor.fetchall()}
            print(f"数据库中已有 {len(existing_tags)} 个标签\n")
            
            # 创建不存在的标签
            new_tags_created = 0
            for tag in all_tags:
                if tag not in existing_tags:
                    cursor.execute(
                        """INSERT INTO dict_tag (name, create_by, create_time) 
                           VALUES (%s, 'system', NOW())""",
                        (tag,)
                    )
                    tag_id = cursor.lastrowid
                    existing_tags[tag] = tag_id
                    new_tags_created += 1
                    print(f"✓ 创建新标签: {tag} (ID: {tag_id})")
            
            if new_tags_created > 0:
                print(f"\n创建了 {new_tags_created} 个新标签\n")
            else:
                print("没有需要创建的新标签\n")
            
            # 同步词典-标签关联
            updated = 0
            not_found = 0
            skipped = 0
            relations_added = 0
            
            print("=" * 80)
            print("开始同步词典标签关联...")
            print("=" * 80 + "\n")
            
            for dict_info in dictionaries:
                dict_id = dict_info['id']
                tags = dict_info['tags']
                
                if dict_id not in db_books:
                    # 跳过一些前端可能有但数据库没有的词典（如小学词典）
                    if not dict_id.startswith(('primary', 'junior', 'senior')):
                        not_found += 1
                        print(f"⚠ 词典不存在: {dict_id}")
                    else:
                        skipped += 1
                    continue
                
                # 获取当前词典已有的标签
                cursor.execute(
                    """SELECT tag_id FROM dict_book_tag WHERE book_id = %s""",
                    (dict_id,)
                )
                current_tag_ids = {row['tag_id'] for row in cursor.fetchall()}
                
                # 目标标签ID集合
                target_tag_ids = {existing_tags[tag] for tag in tags if tag in existing_tags}
                
                # 需要添加的标签
                tags_to_add = target_tag_ids - current_tag_ids
                
                # 需要删除的标签
                tags_to_remove = current_tag_ids - target_tag_ids
                
                # 删除不应该存在的标签关联
                if tags_to_remove:
                    cursor.execute(
                        f"""DELETE FROM dict_book_tag 
                            WHERE book_id = %s AND tag_id IN ({','.join(['%s'] * len(tags_to_remove))})""",
                        (dict_id, *tags_to_remove)
                    )
                
                # 添加新的标签关联
                for tag_id in tags_to_add:
                    cursor.execute(
                        """INSERT INTO dict_book_tag (book_id, tag_id) 
                           VALUES (%s, %s)""",
                        (dict_id, tag_id)
                    )
                    relations_added += 1
                
                if tags_to_add or tags_to_remove:
                    tag_names = [tag for tag in tags if tag in existing_tags]
                    print(f"✓ 同步: {dict_id} ({db_books[dict_id]})")
                    print(f"  标签: {', '.join(tag_names)}")
                    if tags_to_add:
                        print(f"  新增: {len(tags_to_add)} 个标签关联")
                    if tags_to_remove:
                        print(f"  删除: {len(tags_to_remove)} 个标签关联")
                    updated += 1
            
            conn.commit()
            
            print()
            print("=" * 80)
            print("同步完成！")
            print("=" * 80)
            print(f"统计信息:")
            print(f"  - 更新的词典: {updated} 个")
            print(f"  - 新增的标签关联: {relations_added} 个")
            print(f"  - 创建的新标签: {new_tags_created} 个")
            print(f"  - 未找到的词典: {not_found} 个")
            print(f"  - 跳过的词典: {skipped} 个")
            print("=" * 80)
            
    except Exception as e:
        print(f"\n错误: {e}")
        conn.rollback()
        raise
    finally:
        conn.close()

if __name__ == '__main__':
    sync_dict_tags()

